package com.xlx.openLink.handler;


import com.xlx.openLink.base.SnmpException;
import com.xlx.openLink.snmp.SNMPComunication;
import com.xlx.openLink.snmp.tk.AnalyzeMib;
import com.xlx.openLink.snmp.utils.SNMPUtils;
import lombok.extern.slf4j.Slf4j;
import net.percederberg.mibble.MibValueSymbol;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Vector;

/**
 * @author Admin
 */
@Slf4j
@Component
public class RefreshHandler {
    @Autowired
    private AnalyzeMib analyzeMib;

    public void reFresh(Object obj, Snmp snmp, Target target) throws SnmpException {
        try {
            String oid = SNMPUtils.getMibOIDofClass(obj.getClass());
            MibValueSymbol mibValueSymbol = analyzeMib.getMibSymbolByOid(oid);
            String mappingOID = SNMPUtils.getTableOrGroupIndexOID(obj, mibValueSymbol);
            Class clazz = obj.getClass();
            List list = SNMPUtils.getFieldsInMibNodeNew(clazz, mibValueSymbol);
            //udp根据版本创建
            PDU pdu = SNMPComunication.createPdu(target.getVersion());
            for (int i = 0; i < list.size(); i++) {
                MibValueSymbol symbol = (MibValueSymbol) list.get(i);
                String str = symbol.getValue().toString() + "." + mappingOID;
                pdu.add(new VariableBinding(new OID(str)));
            }
            ResponseEvent responseEvent = snmp.get(pdu, target);
            SNMPUtils.checkSNMPErro(responseEvent);
            Vector events = responseEvent.getResponse().getVariableBindings();
            for (int i = 0; i < events.size(); i++) {
                VariableBinding variableBinding = (VariableBinding) events.get(i);
                String oidStr = variableBinding.getOid().toString();
                String name = mibValueSymbol.getMib().getSymbolByOid(oidStr).getName();
                Variable value = variableBinding.getVariable();
                if (value.toString().equalsIgnoreCase("noSuchObject")) {
                    throw new SnmpException(",设备IP:" + name);
                }
                SNMPUtils.setFieldValue(obj, name, value);
            }
        } catch (Exception e) {
            String msg = "从设备中获取对象出错,对象:" + obj.getClass().getName() + ",设备IP:" + target.getAddress() + "错误" + e.getMessage();
            throw new SnmpException(msg);
        }
    }
}
